package com.atguigu.tingshu.user.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Log4j2
public class ReturnAndConfirmConfig{

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 配置两套模式的具体实现方案
     */
    @PostConstruct
    public void init(){
        //confirm模式
        rabbitTemplate.setMandatory(true);
        /**
         * correlationData: 发送消息的附加数据
         * isTure: 消息是否抵达了交换机
         * msg: 抵达了交换机-null 没有抵达-错误原因
         */
        rabbitTemplate.setConfirmCallback((correlationData, isTure, msg)->{
            if(!isTure){
                //消息没有抵达交换机--1.重发 2.记录: mysql redis 日志.....
                log.error("消息没有抵达交换机,原因为:" + msg);
            }
        });
        //return模式: 消息抵达了交换机但是消息没有抵达队列
        rabbitTemplate.setReturnsCallback((returnedMessage)->{
            //获取消息
            Message message = returnedMessage.getMessage();
            String msg = new String(message.getBody());
            //获取消息的附加信息
            String exchange = returnedMessage.getExchange();
            String routingKey = returnedMessage.getRoutingKey();
            int replyCode = returnedMessage.getReplyCode();
            String replyText = returnedMessage.getReplyText();
            log.error("消息没有抵达队列,消息的交换机为:{}, 消息的routingkey为:{},消息的错误码为:{},消息的错误原因为:{},消息的内容为:{}",
                    exchange, routingKey, replyCode, replyText, msg);
        });
    }

}
